import React, { Component } from 'react'
import store from '../../../redux'
import Api from '../../../config/api'
import axios from 'axios'
import Com from '../../../common/common'
import styles from './sass/logbook.scss'

import Navbar from '../../../Component/navbar'

import Button from 'antd/lib/button'
import Table from 'antd/lib/table'
import Spin from 'antd/lib/spin'
import Icon from 'antd/lib/icon'
import Input from 'antd/lib/input'
import Select from 'antd/lib/select'
import DatePicker from 'antd/lib/date-picker'
import Form from 'antd/lib/form'
import message from 'antd/lib/message'
import Modal from 'antd/lib/modal'

import moment from 'moment';
import 'moment/locale/zh-cn';
moment.locale('zh-cn');

const antIcon = <Icon type="loading" style={{ fontSize: 24, marginTop: 200 }} spin />;
const Option = Select.Option;
const FormItem = Form.Item;

let oper = null;

class OperBar extends Component {
    constructor(props) {
        super(props);
        this.state = {
            startDate: '',
            endDate: '',
            startMonent: null,
            endMoment: null,
            OperateLogEnum: [{ index: '', desc: '全部' }]
        }
    }
    componentDidMount() {
        this.getSelect();

    }
    getSelect() {
        axios.post(Api['commonSelect'] + '?em=SmsLogTypeEnum').then((res) => {
            if (res) {
                let data = JSON.parse(JSON.stringify(res.data));
                data.unshift({ index: '', desc: '全部' });
                this.setState({
                    OperateLogEnum: data
                }, () => { this.search(); })
            }
        }).catch((error) => {
            console.log(error)
        })
    }
    getTime(type, moment, time) {
        if (type === 'start') {
            this.setState({
                startDate: time,
                startMoment: moment
            })
        }
        else {
            this.setState({
                endDate: time,
                endMoment: moment
            })
        }
    }
    disabledstartTime(current) {
        if (this.state.endMoment) {
            return current > this.state.endMoment
        }
        else {
            return false
        }
    }
    disabledendTime(current) {
        if (this.state.startMoment) {
            return current < this.state.startMoment
        }
        else {
            return false
        }
    }
    search() {
        let obj = {
            type: this.typeInput.rcSelect.state.value[0],
            method: this.methodInput.input.value,
            parameter: this.reqInput.input.value,
            response: this.resInput.input.value,
            account: this.accountInput.input.value,
            ip: this.ipInput.input.value,
            startTime: this.state.startDate,
            endTime: this.state.endDate
        }
        this.props.search(obj)
    }
    render() {
        return (
            <Navbar ref={(item) => {oper=item}}>
                <Form layout="inline">
                    <FormItem label="类型">
                        <Select ref={(input) => { this.typeInput = input }} defaultValue="">
                            {this.state.OperateLogEnum.map((item, index) => { return <Option key={index} value={item.index}>{item.desc}</Option> })}
                        </Select>
                    </FormItem>
                    <FormItem label="请求方法"><Input style={{ width: '120px' }} ref={(input) => { this.methodInput = input }} /></FormItem>
                    <FormItem label="请求参数"><Input maxLength={100} style={{ width: '120px' }} ref={(input) => { this.reqInput = input }} /></FormItem>
                    <FormItem label="响应内容"><Input maxLength={100} style={{ width: '120px' }} ref={(input) => { this.resInput = input }} /></FormItem>
                    <FormItem label="操作人"><Input style={{ width: '120px' }} ref={(input) => { this.accountInput = input }} /></FormItem>
                    <FormItem label="操作IP"><Input style={{ width: '120px' }} ref={(input) => { this.ipInput = input }} /></FormItem>
                    <FormItem label="开始时间">
                        <DatePicker format="YYYY-MM-DD" disabledDate={this.disabledstartTime.bind(this)} onChange={this.getTime.bind(this, 'start')} />
                    </FormItem>
                    <FormItem label="结束时间">
                        <DatePicker format="YYYY-MM-DD" disabledDate={this.disabledendTime.bind(this)} onChange={this.getTime.bind(this, 'end')} />
                    </FormItem>
                    <FormItem>
                        <Button type="primary" icon="search" onClick={this.search.bind(this)}>查询</Button>
                    </FormItem>
                </Form>
            </Navbar >
        )
    }
}

class Table1 extends Component {
    constructor(props) {
        super(props)
        this.state = {
            dataNum: 0,
            tableHeight: 300,
            tableData: this.props.tableData,
            currentPage: 1
        }
    }
    componentDidMount() {
        setTimeout(() => {
            let operbarHeight = oper.box.offsetHeight + 10 + 10;
            this.setState({
                tableHeight: store.getState().mainTableSize - operbarHeight - 45 - 33 - 71 - 15 - 30
            })
            this.unscribe = store.subscribe(this.fullTable.bind(this))
        }, 100)
    }
    componentWillReceiveProps(nextprops) {
        this.setState({
            tableData: nextprops.tableData,
            dataNum: nextprops.dataNum,
            currntPage: nextprops.currentPage
        })
    }
    componentWillUnmount() {
        this.unscribe()
    }
    fullTable() {
        let operbarHeight = oper.box.offsetHeight + 10 + 10;
        this.setState({
            tableHeight: store.getState().mainTableSize - operbarHeight - 45 - 33 - 71 - 15 - 30
        })
    }
    showResponse(data, text) {
        Modal.info({
            title: text,
            maskClosable: true,
            className: styles['logbook-response-detail'],
            content: (
                <div>
                    <p id="aa" className={styles['logbook-response-detail-content']}>{data}</p>
                </div>
            ),
            cancelText: '取消',
            onCancel() {

            },
            okText: '复制文字',
            onOk(pro) {
                function selectText(element) {
                    var text = document.getElementById(element);
                    if (document.body.createTextRange) {
                        let range = document.body.createTextRange();
                        range.moveToElementText(text);
                        range.select();
                    } else if (window.getSelection) {
                        let selection = window.getSelection();
                        let range = document.createRange();
                        range.selectNodeContents(text);
                        selection.removeAllRanges();
                        selection.addRange(range);
                    }
                }
                selectText("aa");
                document.execCommand('copy')
                message.success('内容已复制到剪切板');
            },
        });
    }
    render() {
        const columns = [
            { title: 'ID', dataIndex: 'id', key: '1', width: 100 },
            { title: '操作类型', dataIndex: 'typeName', key: '4', width: 100 },
            { title: '请求方法', dataIndex: 'method', key: '5', width: 200 },
            {
                title: '请求参数', key: '10', width: 240, render: (record) => {
                    return (<a onClick={this.showResponse.bind(this, record.parameter, '请求参数')}>{record.parameterAbb}</a>)
                }
            },
            {
                title: '响应内容', key: '11', width: 240, render: (record) => {
                    return (
                        <a onClick={this.showResponse.bind(this, record.response, '响应内容')}>{record.responseAbb}</a>
                    )
                }
            },
            { title: '操作人', dataIndex: 'account', key: '7', width: 100 },
            { title: '操作IP', dataIndex: 'ip', key: '15', width: 100 },
            { title: '操作时间', dataIndex: 'createTime', key: '9', width: 200 },
        ];
        return (
            <div className="common-table">
                <Table title={(data) => { return '日志列表' }} columns={columns} dataSource={this.state.tableData} pagination={{
                    onChange: this.props.changePage,
                    onShowSizeChange: this.props.changePageSize,
                    defaultPageSize: 20,
                    pageSizeOptions: ['20', '50', '100'],
                    showSizeChanger: true,
                    showQuickJumper: true,
                    current: this.state.currntPage,
                    total: this.state.dataNum,
                    showTotal: total => `共 ${total} 条数据`
                }} scroll={{ x: 1440, y: this.state.tableHeight }}></Table>
            </div >
        )
    }
}


class Box extends Component {
    constructor(props) {
        super(props)
        this.state = {
            totalNum: 0,
            tableData: [],
            searchParams: {},
            paginationData: {
                current: 1,
                pageNum: 1,
                pageSize: 20
            },
            simSelectData: [],
            statusSelectData: [],
            loading: true,
            currentPage: 1,
        }
    }
    setParams(obj) {
        let data = JSON.parse(JSON.stringify(obj));
        this.setState({
            searchParams: data,
        }, () => {
            this.search('btn');
        })
    }
    search(type) {
        let data = JSON.parse(JSON.stringify(this.state.searchParams));
        if (type === 'btn') {
            data.pageNum = 1;
            this.setState({
                currentPage: 1
            })
        } else {
            data.pageNum = this.state.paginationData.pageNum;
        }
        data.pageSize = this.state.paginationData.pageSize;
        this.setState({
            loading: true,
        })
        axios.post(Api['getLogByParams'], data).then((res) => {
            if (res) {
                let data = JSON.parse(JSON.stringify(res.data));
                data.list.forEach((item, index) => {
                    item.key = index;
                    if (item.parameter) {
                        item.parameterAbb = Com.abbrData(item.parameter, 30);
                    }
                    if (item.response) {
                        item.responseAbb = Com.abbrData(item.response, 30);
                    }
                })
                this.setState({
                    loading: false,
                    tableData: data.list,
                    totalNum: data.total
                })
            }
        }).catch((error) => {
            console.log(error)
        })
    }
    changePageSize(current, size) {
        let pagination = JSON.parse(JSON.stringify(this.state.paginationData))
        pagination.pageNum = current;
        pagination.pageSize = size;
        this.setState({
            paginationData: pagination,
            currentPage: current
        }, () => { this.search('pag') })
    }
    changePage(pageNum, pageSize) {
        let pagination = JSON.parse(JSON.stringify(this.state.paginationData))
        pagination.pageNum = pageNum;
        pagination.pageSize = pageSize;
        this.setState({
            paginationData: pagination,
            currentPage: pageNum
        }, () => { this.search('pag') })
    }
    render() {
        return <div>
            <OperBar paginationData={this.state.paginationData} search={this.setParams.bind(this)}></OperBar>
            <Spin spinning={this.state.loading} indicator={antIcon}>
                <Table1 currentPage={this.state.currentPage} tableData={this.state.tableData} dataNum={this.state.totalNum} changePageSize={this.changePageSize.bind(this)} changePage={this.changePage.bind(this)}></Table1>
            </Spin>
        </div>
    }
}

export default Box